# -*-coding:utf-8 -*-

from django.shortcuts import render
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from .models import *
import json
import urllib
import requests
from django.views.decorators.csrf import csrf_exempt
import os


# Create your views here.


def show_data(request):
    data = RelicsystemUser.objects.all()
    print(data)
    for item in data:
        print(item.password)
    return JsonResponse({1: 1, 2: 2})


def pass_audit(request):
    if request.method == 'GET':
        delid = request.GET.get('id')
        print(request.GET.get('id'))
        NewComment = AndroidCommentTable()
        NewComment.p_id = request.GET.get('p_id')
        NewComment.comment = request.GET.get('comment')
        NewComment.user_id = request.GET.get('user_id')
        NewComment.save()
        AndroidTempCommentTable.objects.get(id=delid).delete()
        return HttpResponseRedirect('/Admin_Management/androidtempcommenttable/')
    else:
        return HttpResponse('POST')
    # print(request)


def forbidden_audit(request):
    if request.method == 'GET':
        delid = request.GET.get('id')
        print(request.GET.get('id'))
        AndroidTempCommentTable.objects.get(id=delid).delete()
        return HttpResponseRedirect('/Admin_Management/androidtempcommenttable/')
    else:
        return HttpResponse('POST')
    # print(request)


def delete_comment(request):
    if request.method == 'GET':
        delid = request.GET.get('id')
        # print(request.GET.get('id'))
        AndroidCommentTable.objects.get(id=delid).delete()
        return HttpResponseRedirect('/Admin_Management/androidcommenttable/')


def revoke_comment(request):
    if request.method == 'GET':
        delid = request.GET.get('id')
        # print(request.GET.get('id'))
        temp = AndroidCommentTable.objects.get(id=delid)
        temp_ = AndroidTempCommentTable(p_id=temp.p_id, user_id=temp.user_id, comment=temp.comment)
        temp_.save()
        temp.delete()
        return HttpResponseRedirect('/Admin_Management/androidcommenttable/')


def automatic_check_comment(request):
    def get_token():
        client_id = 'eEiaGSVVtxYGD7wnGkGbIQGl'
        secret_key = 'VqqVGOym7LMDk2qYbqsPU5gk9WQYYGPA'
        url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' \
              + client_id + '&client_secret=' + secret_key
        response = urllib.request.urlopen(url)
        data = json.loads(response.read().decode('utf-8'))
        return data['access_token']

    def check_text(text):
        request_url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined"
        params = {"text": text}
        access_token = get_token()
        request_url = request_url + "?access_token=" + access_token
        headers = {'content-type': 'application/x-www-form-urlencoded'}
        response = requests.post(request_url, data=params, headers=headers)
        if response:
            return response.json()

    if request.method == 'POST':
        data = request.body
        data = json.loads(data)
        user_id = data['user_id']
        p_id = data['p_id']
        text = data['text']
        res = check_text(text)
        if res['conclusion'] == '不合规':
            # print(res['data'][0]['msg'])
            print(res['data'][0]['hits'][0]['probability'])
            if res['data'][0]['hits'][0]['probability'] >= 0.95:
                user = AndroidAdmin.objects.get(id=user_id)
                user.comment_right = 0
                user.save()
                return JsonResponse({
                    'response': '0',
                    'content': res['data'][0]['msg']
                })
            else:
                comment = AndroidTempCommentTable(p_id=p_id, comment=text, user_id=user_id)
                comment.save()
                return JsonResponse({
                    'response': 0,
                    'content': '内容可能存在违规，需要人工审核'
                })
        else:
            comment = AndroidCommentTable(p_id=p_id, comment=text, user_id=user_id)
            comment.save()
        # print(res)
        return JsonResponse({
            'response': 1,
            'content': '发表成功',
        })


@csrf_exempt
def data_recovery(request):
    if request.method == 'POST':
        received_file = request.FILES.get("upload_file")
        if not received_file:
            return HttpResponse('file not found')
        # print(type(received_file))
        save_path = '.\\data_recovery\\ % s' % received_file.name
        with open(save_path, 'wb+') as f:
            for chunk in received_file.chunks():
                # print(chunk)
                f.write(chunk)
        f.close()
        with open(save_path,'r') as f:
            # data = list(map(str,f.readlines()))
            data = f.readlines()
            types = data[0][:-1]
            _data = data[1:]
            # print(types)
            if types == 'Admin_Management.KnowLedgeAdmin':
                RelicsystemUser.objects.all().delete()
                data_list = [item[:-1] for item in _data]
                for item in data_list:
                    data = json.loads(item)
                    temp = RelicsystemUser(
                        username=data['username'],password=data['password'],
                        phonenumber=data['phonenumber'],firstname=data['firstname'],lastname=data['lastname'])
                    temp.save()
                # return render(request,'http://127.0.0.1:8000/#Admin_Management/relicsystemuser/')
            elif types == 'Admin_Management.AndroidAdminAdmin':
                AndroidAdmin.objects.all().delete()
                data_list = [item[:-1] for item in _data]
                for item in data_list:
                    data = json.loads(item)
                    temp = AndroidAdmin(
                        username=data['username'], password=data['password'],email=data['email'],
                        truename=data['truename'], sex=data['sex'], phone=data['phone'],comment_right=data['comment_right'])
                    temp.save()
            elif types == 'Admin_Management.relicAdmin':
                # Relic.objects.all().delete()
                data_list = [item[:-1] for item in _data]
                for item in data_list:
                    data = json.loads(item)
                    temp = Relic(
                        relicname=data['relicname'], times=data['times'], timepoint=data['timepoint'],
                        material=data['material'], type=data['type'], museum=data['museum'],
                        detailurl=data['detailurl'], imageurl=data['imageurl'],introduction=data['introduction'])
                    temp.save()
        return HttpResponseRedirect('/backend/data_recovery/')
    else:
        return render(request, 'index.html')
